package com.definesys.smecrailtransit.module.SiteDetails;

import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentSiteDetailsBinding;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.DateController;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.ELeParaArchiivesFragment;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleFaultStatisticsFragment;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleRealTimeFragment;
import com.definesys.smecrailtransit.module.SiteDetails.Fragment.EleRuntimelengthFragment;
import com.definesys.smecrailtransit.module.SiteDetails.bean.EleAttentionBean;
import com.definesys.smecrailtransit.widget.Titanic.Titanic;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnRangeSelectedListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;
import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SELECTION_MODE_RANGE;

/**
 * Created by xupeizuo on 2017/8/21.
 */

public class SiteDetailsFragment extends SmecBaseFragment<SiteDetailsPresenter>{

    private FragmentSiteDetailsBinding fragmentSiteDetailsBinding;
    private ArrayList<Fragment> fragmentArrayList=new ArrayList<>();
    private int currentPage=0;

    public static final String SiteSwitch="SiteSwitch";
    public static final String REFRESH="REFRESH";
    public static final String CHANGE_MONTH="changeMonthSD()";
    private static boolean isFirst = true;
    private String faultType = "ALL";


    private HashMap<String,Object> map=new HashMap<>();
    private int stationId=12335;
    private String date="";

    private SiteDetailsViewModel siteDetailsViewModel;

    private DateController formController;
    private DateController timeController;
    private Titanic titanic;

    //日历
    private MaterialCalendarView calendar;

    //故障类型选择弹出框
    private PopupWindow faultTypeSlector;
    //故障类型列表
    private ListView faultTypeList;
    private ArrayList<String> faultTypeData;
    private ArrayAdapter<String> faultTypeAdapter;


    @Override
    protected SiteDetailsPresenter getPersenter() {
        return new SiteDetailsPresenter(getActivity());
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentSiteDetailsBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_site_details,container,false);
        siteDetailsViewModel=new SiteDetailsViewModel(getActivity(),fragmentSiteDetailsBinding,mRxBus);
        _initView();
        fragmentSiteDetailsBinding.setSiteModel(siteDetailsViewModel);
        return fragmentSiteDetailsBinding.getRoot();
    }

    private void _initView(){

        _setAttentionMsg();
        schedulerThread(Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                _setMonth();
                _setCurrentMonth();
                _setMonthClick();
            }
        })).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
            }
        });

        //设置日历
        setCalendar();

        _initViewPage();
    }

    /**
     * 初始化Viewpage
     */
    private void _initViewPage(){
        fragmentSiteDetailsBinding.siteSwitched.getPaint().setFakeBoldText(true);
        fragmentSiteDetailsBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);

        fragmentArrayList.add(EleRealTimeFragment.newInstance(mPresenter));
        fragmentArrayList.add(EleFaultStatisticsFragment.newInstance(mPresenter));
        fragmentArrayList.add(EleRuntimelengthFragment.newInstance(mPresenter));
        fragmentArrayList.add(ELeParaArchiivesFragment.newInstance(mPresenter));

        fragmentSiteDetailsBinding.viewPage.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentArrayList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentArrayList.size();
            }
        });
        fragmentSiteDetailsBinding.viewPage.setOffscreenPageLimit(fragmentArrayList.size());
        fragmentSiteDetailsBinding.viewPage.setPageMargin(40);
        fragmentSiteDetailsBinding.viewPage.setCurrentItem(currentPage,false);
        fragmentSiteDetailsBinding.viewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage=position;
                fragmentSiteDetailsBinding.faultType.setVisibility(GONE);

                fragmentSiteDetailsBinding.title.setText(SmecRailConstant.getTitleArrayList().get(position));
                if(titanic == null){
                    titanic = new Titanic();
                }
                titanic.start(fragmentSiteDetailsBinding.title);
                fragmentSiteDetailsBinding.title.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        titanic.cancel();
                    }
                },1000);
                if(position ==0 || position == 3){
                    fragmentSiteDetailsBinding.siteDate.setVisibility(View.INVISIBLE);
                }else {
                    fragmentSiteDetailsBinding.siteDate.setVisibility(View.VISIBLE);
                }
                map.put("way","1");
                refresh();

                setMonth();

            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        fragmentSiteDetailsBinding.siteTitle.setOnClickListener(v -> {
            if(fragmentSiteDetailsBinding.choice.getVisibility() == VISIBLE){
                fragmentSiteDetailsBinding.choice.setVisibility(GONE);
            }
        });


        //故障类型数据
        faultTypeData = new ArrayList<>();
        faultTypeData.add("全部故障");
        faultTypeData.add("非自身性停梯");
        faultTypeData.add("扶梯故障");

        //故障类型选择点击事件
        fragmentSiteDetailsBinding.faultType.setOnClickListener(v -> {
            // 设置内容与适配器
            faultTypeList = new ListView(this.getContext());

            faultTypeAdapter = new ArrayAdapter<String>(this.getContext(), R.layout.layout_fault_type_item, faultTypeData);
            faultTypeList.setAdapter(faultTypeAdapter);

            //设置点击事件
            faultTypeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position){
                        case 0:
                            fragmentSiteDetailsBinding.faultTypeText.setText("全部故障");
                            faultType = "ALL";
                            break;
                        case 1:
                            fragmentSiteDetailsBinding.faultTypeText.setText("非自身性停梯");
                            faultType = "NOSELF";
                            break;
                        case 2:
                            fragmentSiteDetailsBinding.faultTypeText.setText("扶梯故障");
                            faultType = "FT";
                            break;
                    }

                    refresh();

                    fragmentSiteDetailsBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
                    // 选择完后关闭popup窗口
                    faultTypeSlector.dismiss();
                }
            });

            //设置弹窗
            faultTypeSlector= new PopupWindow(faultTypeList,fragmentSiteDetailsBinding.faultType.getWidth(), ActionBar.LayoutParams.WRAP_CONTENT, true);
            // 取得popup窗口的背景图片
            Drawable drawable = ContextCompat.getDrawable(this.getContext(), R.drawable.select_line_shadow);
            faultTypeSlector.setBackgroundDrawable(drawable);
            faultTypeSlector.setFocusable(true);
            faultTypeSlector.setOutsideTouchable(true);
            faultTypeSlector.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    // 关闭popup窗口
                    fragmentSiteDetailsBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
                    faultTypeSlector.dismiss();
                }
            });

            if (faultTypeSlector != null && !faultTypeSlector.isShowing()) {
                fragmentSiteDetailsBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_top);
                faultTypeSlector.showAsDropDown(fragmentSiteDetailsBinding.faultType);
            }

        });

    }


    /**
     * 设置关注信息
     */
    private void _setAttentionMsg(){
        EleAttentionBean eleAttentionBean=mPresenter.getAttention();
        siteDetailsViewModel._initTitle();
        if(eleAttentionBean!=null && eleAttentionBean.getStationId()!=0 && eleAttentionBean.getStationName()!=null){
            stationId=eleAttentionBean.getStationId();
            siteDetailsViewModel.setStationsName(eleAttentionBean.getStationName());
            fragmentSiteDetailsBinding.siteSwitched.setText(eleAttentionBean.getStationName());
        }else {
            stationId=12385;
            siteDetailsViewModel.setStationsName("七莘路站");
            fragmentSiteDetailsBinding.siteSwitched.setText("七莘路站");
        }
    }

    /**
     * 设置月份信息
     */
    private void _setMonth(){
        formController = new DateController(SmecRailApi.MonthCode.MONTHFORM);
        timeController = new DateController(SmecRailApi.MonthCode.STATUSTIME);
    }

    /**
     * 设置当前月份
     */
    private void _setCurrentMonth(){
        String[] nowStr=SmecRailConstant.getNowTime().split(" ")[0].split("-");
        date=nowStr[0]+"-"+nowStr[1];
    }

    /**
     * 设置日历点击事件
     */
    private void _setMonthClick(){
        //设置日历的点击事件
        fragmentSiteDetailsBinding.siteDate.setOnClickListener(v -> {
            if(fragmentSiteDetailsBinding.choice.getVisibility() == View.VISIBLE){
                fragmentSiteDetailsBinding.choice.setVisibility(GONE);
            }else{
                fragmentSiteDetailsBinding.choice.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     *  设置日历
     */
    private void setCalendar(){
        calendar = fragmentSiteDetailsBinding.calendar;
        calendar.state().edit()
                .setFirstDayOfWeek(Calendar.MONDAY)
                .setMaximumDate(CalendarDay.from(Calendar.getInstance().get(Calendar.YEAR)
                        , Calendar.getInstance().get(Calendar.MONTH)
                        , Calendar.getInstance().get(Calendar.DATE)))
                .setCalendarDisplayMode(CalendarMode.MONTHS)
                .commit();
        calendar.setSelectionMode(SELECTION_MODE_RANGE);
        calendar.setSelectionColor(fragmentSiteDetailsBinding.getRoot().getContext().getResources().getColor(R.color.calendar_select));
        calendar.setArrowColor(fragmentSiteDetailsBinding.getRoot().getContext().getResources().getColor(R.color.monthForm_line));
        calendar.setOnRangeSelectedListener(new OnRangeSelectedListener() {
            @Override
            public void onRangeSelected(@NonNull MaterialCalendarView widget, @NonNull List<CalendarDay> dates) {
                SimpleDateFormat sDateFormat =  new SimpleDateFormat("yyyy-MM-dd");

                if(currentPage == 1){
                    formController.setFrom(sDateFormat.format(dates.get(0).getDate()));
                    formController.setTo(sDateFormat.format(dates.get(dates.size()-1).getDate()));
                    fragmentSiteDetailsBinding.startDate.setText(formController.getFrom());
                    fragmentSiteDetailsBinding.endDate.setText(formController.getTo());

                    formController.setDateList(dates);
                }
                if(currentPage == 2){
                    timeController.setFrom(sDateFormat.format(dates.get(0).getDate()));
                    timeController.setTo(sDateFormat.format(dates.get(dates.size()-1).getDate()));
                    fragmentSiteDetailsBinding.startDate.setText(timeController.getFrom());
                    fragmentSiteDetailsBinding.endDate.setText(timeController.getTo());

                    timeController.setDateList(dates);

                }
                map.put("way","2");
                refresh();
                fragmentSiteDetailsBinding.choice.setVisibility(GONE);
            }
        });
    }

    /**
     * 当站点以及日期改变时 刷新数据
     */
    public void refresh(){
        map.put("position",currentPage);
        map.put("stationId",stationId);
        map.put("fromForm",formController.getFrom());
        map.put("toForm", formController.getTo());
        map.put("faultType",faultType);
        map.put("fromTime",timeController.getFrom());
        map.put("toTime", timeController.getTo());
        mRxBus.post(SiteSwitch,map);
    }

    /**
     * 改变日期是刷新数据
     */
    private void changeMonth(){
        map.clear();
        refresh();
    }

    private void setMonth(){
        calendar.clearSelection();
        if(currentPage == 1){
            fragmentSiteDetailsBinding.startDate.setText(formController.getFrom());
            fragmentSiteDetailsBinding.endDate.setText(formController.getTo());
            if(formController.getDateList() != null) {
                for (int i = 0; i < formController.getDateList().size(); i++) {
                    calendar.setDateSelected(formController.getDateList().get(i), true);
                }
            }
        }
        if(currentPage == 2){
            fragmentSiteDetailsBinding.startDate.setText(timeController.getFrom());
            fragmentSiteDetailsBinding.endDate.setText(timeController.getTo());
            if(timeController.getDateList() != null) {
                for (int i = 0; i < timeController.getDateList().size(); i++) {
                    //calendar.setSelectedDate(timeController.getDateList().get(i));
                    calendar.setDateSelected(timeController.getDateList().get(i), true);
                }
            }
        }
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(REFRESH)
            }
    )
    public void refresh(HashMap<String,Object> hashMap){
        map.clear();
        stationId=(Integer) hashMap.get("stationId");
        refresh();
        HashMap<String,Object> update=new HashMap<>();
        update.put("stationId",stationId);
        update.put("stationName",hashMap.get("stationName"));
        mPresenter.updateAttention(update);
    }

    public static SiteDetailsFragment newInstance() {
        Bundle args = new Bundle();
        SiteDetailsFragment fragment = new SiteDetailsFragment();
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 从导航栏进入改Fragment 时 应该只让第一个Fragment刷新数据
     * @param position
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void intFragment(String position){
        if(position.equals("1")){
            fragmentSiteDetailsBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    refresh();
                }
            },300);
        }
    }
}
